<?php

/**
*
 * @author: Korowanire
 * @description: User class for login and Dragon's glory
*/

require_once "base.class.php";


class User extends Base{


		
		/**
		 * 
		 * @return true if user is not logined
		 */
		public function isAnon()
		{
			return $this->id==-1;
		}
		
		/**
		 * 
		 * @return anonimous user object
		 */
		public static function createAnon()
		{
			$u = new User();
			$u->user_name = "anon";
			$u->id = -1;
			
			return $u;
		}
		
		
		public function auth()
		{
		
			if(empty($_COOKIE["kekekeUserID"]) or !is_numeric($_COOKIE["kekekeUserID"]))
			{//not authorized: user id is a not digit or empty
				throw new Exception("Non-auth");
			}
			try{$this->load($_COOKIE["kekekeUserID"], "id");}
				catch(Exception $e){throw new Exception("Auth failed: ".$e->getMessage());}

			if($_COOKIE["kekekeToken"]==md5($this->user_salt . $this->user_pass) and 
				$_COOKIE["kekekeUserName"]==$this->user_name)
			{
				//echo "Login.";//print_r($this);
			}
			else
			{
				throw new Exception("Error in auth");
			}
		}
		
		/**
		* returns user object
		*/
		public static function login($login, $pass)
		{
			$user = new User();
			if(empty($login)) throw new Exception("Error in login: empty username");
			try{
			$user->load($login, 'user_name');
			//insert into `users` values (0, 'Tester', md5(concat('test', 'pass')), 'test', 1, 0)
			}
			catch(Exception $e){if(substr($e->getMessage(), 0, 12)=="Have no data")throw new Exception("No user");}
			$token = md5($user->user_salt . $pass);
			if($user->user_pass!=$token) throw new Exception("Erroneous pass.");
			
			setcookie("kekekeUserID", $user->id);
			setcookie("kekekeUserName", $user->user_name);
			$token = md5($user->user_salt . $user->user_pass);
			setcookie("kekekeToken", $token);
			return $user;
		
		}
		
		public static function logout()
		{
			setcookie("kekekeUserID", null);
			setcookie("kekekeUserName", null);
			setcookie("kekekeToken", null);
			return User::createAnon();
		}
		
			
}




